let boxImg = document.querySelector(".boxImg");
let leftImg = document.querySelector(".boxImg img");
let mask = document.querySelector(".mask");
let box = document.querySelector(".box");
let prewBox = document.querySelector(".prewBox");
let prewImg = document.querySelector(".prewBox img");
let imgBoxList = document.querySelectorAll(".imgList .imgBox");

leftImg.addEventListener("mousemove", function (e) {
    mask.style.display = "block";
    prewBox.style.visibility = "visible";

    // 获取遮罩层mask的移动距离
    // x = 鼠标的水平页面坐标 - 大盒子距离页面的水平偏移量 - 遮罩层一半的宽度
    // y = 鼠标的垂直页面坐标 - 大盒子距离页面的垂直偏移量 - 遮罩层一半的高度
    let maskX = e.pageX - box.offsetLeft - mask.offsetWidth / 2;
    let maskY = e.pageY - box.offsetTop - mask.offsetHeight / 2;

    // 遮罩层mask的移动取值范围
    let maxMoveWidth = box.clientWidth - mask.clientWidth;
    let maxMoveHeight = box.clientHeight - mask.clientHeight;

    //当遮罩层移动超出box时，对遮罩层移动距离做出限制，限制在box内
    if (maskX < 0) {
        maskX = 0;
    } else if (maskX > maxMoveWidth) {
        maskX = maxMoveWidth;
    }
    if (maskY < 0) {
        maskY = 0;
    } else if (maskY > maxMoveHeight) {
        maskY = maxMoveHeight;
    }
    mask.style.left = maskX + 'px';
    mask.style.top = maskY + 'px';

    // 预览图片的最大移动距离
    let prewMaxWidth = prewImg.clientWidth - prewBox.clientWidth;
    let prewMaxHeight = prewImg.clientHeight - prewBox.clientHeight;
    // 预览图片的最大移动距离
    let prewX = maskX * prewMaxWidth / maxMoveWidth;
    let prewY = maskY * prewMaxHeight / maxMoveHeight;

    prewImg.style.transform = `translate(${-prewX}px,${-prewY}px)`;


});

leftImg.addEventListener("mouseleave", function (e) {
    prewBox.style.visibility = "hidden";
    mask.style.display = "none";
})

imgBoxList.forEach((item, index) => {
    item.addEventListener('click', function (e) {
        boxImg.firstElementChild.src = e.target.src;
        prewImg.src = e.target.src;
    })
})